package com.qf.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.dto.ApiResult;
import com.qf.entity.Product;
import com.qf.entity.request.ProductRequest;
import com.qf.entity.response.ProductResponse;
import com.qf.service.IProductService;
import com.qf.utils.QiniuUtil;
import com.qf.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author chen
 * @since 2021-03-18
 */
@RestController
@RequestMapping("/product")
@Api(tags = "商品控制器")

public class ProductController {

    private static final String perfix = "http://qpuevq2yq.hn-bkt.clouddn.com/";


    @Autowired
    private IProductService productService;

    @RequestMapping(value = "/doUpLoad",method = RequestMethod.POST)
    @ApiOperation("上传文件")
    @CrossOrigin
    public ApiResult upload(@RequestBody MultipartFile file) throws IOException {
        //新名字
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "");
        String fileSrc = QiniuUtil.byteUpLoad(file.getBytes(), newFileName);
        return R.ok(perfix +fileSrc);
    }

    @ApiOperation("查询商品列表")
    @CrossOrigin
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public ApiResult list(@RequestBody ProductRequest request){
        IPage<ProductResponse> page = productService.findListForPage(request);
        return R.ok(page);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiOperation("添加商品")
    @CrossOrigin
    public ApiResult add(@RequestBody ProductRequest request ){
        Product product = new Product();
        //拷贝参数到实体类中
        BeanUtils.copyProperties(request,product);
        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());
        productService.save(product);
        return R.ok();
    }

    @ApiOperation("上架下架")
    @RequestMapping(value = "/upOrDown",method = RequestMethod.POST)
    @CrossOrigin
    public ApiResult upOrDown(@RequestBody ProductRequest request){
        productService.upOrDown(request.getId());
        return R.ok();
    }



}
